package com.fowo.api.config;

import com.alibaba.druid.pool.ha.HighAvailableDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置 Druid
 */
@Configuration
public class DruidConfig {

    /**
     * 获取主数据源名称
     */
    @Value("${spring.datasource.dynamic.primary}")
    private String primaryDSName;

    /**
     * 配置高可用数据源
     * 需要配置 spring.datasource.ha = true
     * @link https://github.com/alibaba/druid/blob/master/doc/ha-datasource.md
     */
    @ConditionalOnProperty(prefix = "spring.datasource", value = "ha", havingValue = "true")
    @Bean(destroyMethod = "destroy")
    public HighAvailableDataSource dataSource() {
        HighAvailableDataSource haDataSource = new HighAvailableDataSource();
        // 指定从 ha-datasource.properties 添加数据源
        haDataSource.setDataSourceFile("/ha-datasource.properties");
        // 需要主数据源相同的前缀
        haDataSource.setPropertyPrefix(primaryDSName);
        // 随机选择数据源
        haDataSource.setSelector("random");
        haDataSource.setPoolPurgeIntervalSeconds(60);
        haDataSource.setAllowEmptyPoolWhenUpdate(true);
        haDataSource.init();
        return haDataSource;
    }
}
